<template>
  <j-modal :confirmLoading="confirmLoading" :title="title" :visible="visible" :width="1200" cancelText="关闭"
           switchFullscreen @cancel="handleCancel" @ok="handleOk">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="!disableSubmit" type="primary" @click="handleOk">确认</a-button>
    </template>
    <a-divider orientation="left" style="font-weight: 600;margin-top: 0px;">基本信息</a-divider>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-col :md="8" :sm="24">
          <a-form-item v-if="!itemShow" :labelCol="labelCol" :wrapperCol="wrapperCol" label="选择人员">
            <a-input-search v-decorator="['visitUserRealName',validatorRules.visitUserRealName]"
                            :disabled="disableSubmit"
                            enter-button placeholder="请选择人员" readOnly @search="productSearch2('superiorUser')"/>
            <a-input v-decorator="[ 'visitUserName', {}]" readOnly type="hidden"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="人员职位">
            <a-input v-decorator="['visitPosName']" :disabled="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="所属组织">
            <a-input v-decorator="['visitOrgName']" :disabled="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="16" :sm="24">
          <a-form-item :labelCol="{ xs: {
                                      span: 24
                                    },
                                    sm: {
                                      span: 'L-1'
                                    }}"
                       :wrapperCol="{ xs: {
                                       span: 24
                                      },
                                      sm: {
                                       span: 'w-1'
                                    }}"
                       label="拜访周期">
            <a-week-picker v-decorator="['visitDateStarts',validatorRules.visitDates]" :format="'YYYY-wo'"
                           placeholder="拜访周期"
                           style="width:260px"
                           :disabled="disableSubmit" :valueFormat="'YYYY-MM-DD'"
                           @change="dateRangeChange"></a-week-picker>
            <a-input type="hidden" v-decorator="['visitDateEnd']"></a-input>
            <a-input type="hidden" v-decorator="['visitDateStart']"></a-input>
            <sapn v-if="form.getFieldValue('visitDateStart')">(<span style="color:red">{{ form.getFieldValue('visitDateStart') }}</span> ~
              <span style="color:red">{{ form.getFieldValue('visitDateEnd') }}</span>)
            </sapn>
          </a-form-item>
        </a-col>
        <!--        <a-col :md="16" :sm="24">-->
        <!--          选择范围：-->
        <!--        </a-col>-->

        <a-divider orientation="left" style="font-weight: 400;margin-top: 0px;">拜访信息</a-divider>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排除">
          <a-checkbox-group v-model="checkedList" :disabled="disableSubmit" :options="plainOptions"
                            @change="onChangeTime"></a-checkbox-group>
        </a-form-item>
        <!--        网点新增-->
        <div v-if='keyState === "3"'>
          <a-divider orientation="left" style="font-weight: 400;margin-top: 0px;">门店</a-divider>
          <a-button v-if="!disableSubmit" style="margin: 10px 30px 0px 30px;" type="primary"
                    @click="handleConfig(record)">新增
          </a-button>
          <div style="padding: 10px 20px;">
            <a-table ref="table" :columns="columns" :dataSource="dataSource2"
                     :rowSelection="{selectedRowKeys:selectedRowKeys, onChange: onSelectChange1}"
                     :scroll="{x:400,y:240 }"
                     bordered
                     rowKey="id" size="middle"
                     @change="handleTableChange">
            <span v-if="!disableSubmit" slot="action" slot-scope="text, record">
              <a style="color: red;" @click="handleDelete2(record)">删除</a>
            </span>
            </a-table>
          </div>

          <a-divider orientation="left" style="font-weight: 400;margin-top: 0px;">经销商</a-divider>
          <a-button v-if="!disableSubmit" style="margin: 10px 30px 0px 30px;" type="primary"
                    @click="handleConfigTer(record)">新增
          </a-button>
          <div style="padding: 10px 20px;">
            <a-table ref="table" :columns="columns2" :dataSource="dataSource"
                     :rowSelection="{selectedRowKeys:selectedRowKeys2, onChange: onSelectChange2}"
                     :scroll="{x:400,y:240 }" bordered
                     rowKey="id" size="middle"
                     @change="handleTableChange">
            <span v-if="!disableSubmit" slot="action" slot-scope="text, record">
              <a style="color: red;" @click="handleDelete(record)">删除</a>
            </span>
            </a-table>
          </div>
        </div>
        <!--    频率新增    -->
        <div v-if='keyState === "2"'>
          <a-divider orientation="left" style="font-weight: 400;margin-top: 0px;">门店</a-divider>
          <a-button v-if="!disableSubmit" style="margin: 10px 30px 0px 30px;" type="primary"
                    @click="handleConfig(record)">新增
          </a-button>
          <div style="padding: 10px 20px;">
            <a-table ref="table" :columns="columns3" :dataSource="dataSource2"
                     :rowSelection="{selectedRowKeys:selectedRowKeys, onChange: onSelectChange1}"
                     :scroll="{x:400,y:240 }"
                     bordered
                     rowKey="id" size="middle"
                     @change="handleTableChange">
              <span slot="firstDate" slot-scope="value, record,index">
              <a-date-picker :disabled="disableSubmit" :value="record.firstDate" format="YYYY-MM-DD"
                             valueFormat="YYYY-MM-DD" @change="timeChange(record,$event)"/>

                <!--                @change='timeChange(text,"firstDate",record.id, )-->
            </span>
              <span slot="visitFrequency" slot-scope="text,record,index">
                <a-input v-model="text" :disabled="disableSubmit" style="width: 100%"
                         @change="onCellChange2(record.id, 'visitFrequency', text)"/>
              </span>
              <span v-if="!disableSubmit" slot="action" slot-scope="text, record">
              <a style="color: red;" @click="handleDelete2(record)">删除</a>
            </span>
            </a-table>
          </div>

          <a-divider orientation="left" style="font-weight: 400;margin-top: 0px;">经销商</a-divider>
          <a-button v-if="!disableSubmit" style="margin: 10px 30px 0px 30px;" type="primary"
                    @click="handleConfigTer(record)">新增
          </a-button>
          <div style="padding: 10px 20px;">
            <a-table ref="table" :columns="columns4" :dataSource="dataSource"
                     :rowSelection="{selectedRowKeys:selectedRowKeys2, onChange: onSelectChange2}"
                     :scroll="{x:400,y:240 }" bordered
                     rowKey="id" size="middle"
                     @change="handleTableChange">
              <span slot="firstDate" slot-scope="text, record">
              <a-date-picker :disabled="disableSubmit" :value="record.firstDate" format="YYYY-MM-DD"
                             valueFormat="YYYY-MM-DD" @change="timeChange2(record,$event)"/>
            </span>

              <span slot="visitFrequency" slot-scope="text,record,index">
                <a-input v-model="text" :disabled="disableSubmit" style="width: 100%"
                         @change="onCellChange(record.id, 'visitFrequency', text)"/>
              </span>
              <span v-if="!disableSubmit" slot="action" slot-scope="text, record">
              <a style="color: red;" @click="handleDelete(record)">删除</a>
            </span>
            </a-table>
          </div>
        </div>
        <!--   线路组新增-->
        <div v-if='keyState === "1"'>
          <a-divider orientation="left" style="font-weight: 400;margin-top: 0px;">周期线路组</a-divider>
          <a-button v-if="!disableSubmit" style="margin: 10px 30px 0px 30px;" type="primary"
                    @click="handleConfigline(record)">新增
          </a-button>
          <div style="padding: 10px 20px;">
            <a-table ref="table" :columns="columns5" :dataSource="dataSource2"
                     :rowSelection="{selectedRowKeys:selectedRowKeys, onChange: onSelectChange1}"
                     :scroll="{x:400,y:240 }"
                     bordered
                     rowKey="id" size="middle"
                     @change="handleTableChange">
              <template slot="sort" slot-scope="text, record,index">
                <a :disabled="disableSubmit" @click="moveSort(record,index,1)">下移</a>
                <a-divider type="vertical"/>
                <a :disabled="disableSubmit" @click="moveSort(record,index,2)">上移</a>
              </template>
              <span v-if="!disableSubmit" slot="action" slot-scope="text, record">
              <a style="color: red;" @click="handleDelete2(record)">删除</a>
            </span>
            </a-table>
          </div>
        </div>
        <my-shuttle-modal
          ref="orgShuttleModal"
          :positionCode="visitPosCode"
          :columns="orgColumns"
          :columns2="orgColumns2"
          :searchConfig="orgSearchConfig"
          keyVal="custCode"
          leftUrl="/customerExtendController/findPageListByPositionCode "
          title="选择经销商"
          @chooseOk="chooseOk"
        ></my-shuttle-modal>
        <my-shuttle-modal
          ref="cusShuttleModal"
          :columns="cusColumns"
          :columns2="cusColumns2"
          :positionCode="visitPosCode"
          :searchConfig="cusSearchConfig"
          keyVal="terminalCode"
          leftUrl="/cnTerminalExtendController/findPageListByPositionCode "
          title="选择门店"
          @chooseOk="chooseOk2"
        ></my-shuttle-modal>
        <my-shuttle-modal
          ref="lineShuttleModal"
          :columns="lineColumns"
          :columns2="lineColumns2"
          :leftUrl="lineList"
          :positionCode="visitPosCode"
          :searchConfig="lineSearchConfig"
          keyVal="groupCode"
          title="选择线路组"
          @chooseOk="chooseOk3"
        ></my-shuttle-modal>
      </a-form>

    </a-spin>
    <StorePlanMod ref="ConfigPosCust" modal-width="90%" @ok="dataUserRess"></StorePlanMod>
    <StorePlanMod ref="ConfigModal" modal-width="90%" @ok="saveUserRelation"></StorePlanMod>

    <proChose ref="prochoose2" v-bind="modalProps" @okbro="okbropro2"></proChose>
  </j-modal>
</template>

<script>
import {
  httpAction,
  postAction
} from '@/api/manage'
import moment from 'moment'
import proChose from '@comp/cn-components/ProChose'
import pick from 'lodash.pick'
import chooseModal from '@/components/cn-components/ChooseModal'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import WedPalnMakingMod from './WedPalnMakingMod.vue'
import StorePlanMod from './StorePlanMod.vue'
import myShuttleModal from '@/components/cn-components/CnShuttleModal'
import JDate from '@comp/cn-form/JDate'

export default {
  name: 'SfaSignConfigModal',
  props: {
    keyState: {//定义新增状态
      type: String,
      default: ''
    }
  },
  components: {
    JTreeSelect,
    chooseModal,
    proChose,
    WedPalnMakingMod,
    StorePlanMod,
    myShuttleModal,
    JDate
  },
  data() {
    return {
      disableSubmit: false,
      plainOptions: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
      checkedList: [],
      lineList: window._CONFIG['domianSfaURL'] + '/small/visit/sfaVisitGroupEntity/findPageListSmall',
      name: '',
      time: [],
      title: '操作',
      objs: [],
      value: 1,
      visitPosCode: '', //职位编码
      dataSource: [],
      dataSource2: [],
      detailVos: [],
      makeType: '',//新增类型
      weekVos: [],//线路计划周排队集合
      visible: false,
      model: {},
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 5
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 16
        }
      },
      // 门店
      columns: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      //门店弹框搜索条件
      cusSearchConfig: [
        {
          type: 'input',
          placeholder: '门店编号',
          name: 'terminalCode'
        },
        {
          type: 'input',
          placeholder: '门店名称',
          name: 'terminalName'
        }
      ],
      cusColumns: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        }
      ],
      cusColumns2: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      //经销商
      columns2: [
        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      orgSearchConfig: [
        {
          type: 'input',
          placeholder: '经销商编号',
          name: 'custCode'
        },
        {
          type: 'input',
          placeholder: '经销商名称',
          name: 'custName'
        }
      ],
      orgColumns: [

        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        }
      ],
      orgColumns2: [
        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      //频率新增门店
      columns3: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        },
        {
          title: '首次拜访日期',
          align: 'center',
          dataIndex: 'firstDate',
          scopedSlots: {
            customRender: 'firstDate'
          }
        },
        {
          title: '拜访频率（天/1次）',
          align: 'center',
          dataIndex: 'visitFrequency',
          scopedSlots: {
            customRender: 'visitFrequency'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      //频率新增经销商
      columns4: [
        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'custCode'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'custName'
        },
        {
          title: '首次拜访日期',
          align: 'center',
          dataIndex: 'firstDate',
          scopedSlots: {
            customRender: 'firstDate'
          }
        },
        {
          title: '拜访频率（天/1次）',
          align: 'center',
          dataIndex: 'visitFrequency',
          scopedSlots: {
            customRender: 'visitFrequency'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      //线路组表格
      columns5: [
        {
          title: '线路组编码',
          align: 'center',
          dataIndex: 'groupCode'
        },
        {
          title: '线路组名称',
          align: 'center',
          dataIndex: 'groupName'
        },
        {
          title: '调整排序',
          align: 'center',
          dataIndex: 'name',
          scopedSlots: {
            customRender: 'sort'
          }
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      //弹窗表格
      lineColumns: [
        {
          title: '线路组编码',
          align: 'center',
          dataIndex: 'groupCode'
        },
        {
          title: '线路组名称',
          align: 'center',
          dataIndex: 'groupName'
        }
      ],
      //弹窗选中表格
      lineColumns2: [
        {
          title: '线路组编码',
          align: 'center',
          dataIndex: 'groupCode'
        },
        {
          title: '线路组名称',
          align: 'center',
          dataIndex: 'groupName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          // fixed: 'right',
          align: 'center',
          scopedSlots: {
            customRender: 'delete'
          }
        }
      ],
      //线路组搜索条件
      lineSearchConfig: [
        {
          type: 'input',
          placeholder: '线路组编码',
          name: 'groupCode'
        },
        {
          type: 'input',
          placeholder: '线路组名称',
          name: 'groupName'
        }
      ],
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      selectedRowKeys2: [],
      /* table选中records*/
      selectionRows2: [],
      positionsColumns: [
        {
          title: '门店编码',
          align: 'center',
          dataIndex: 'terminalCode'
        },
        {
          title: '门店名称',
          align: 'center',
          dataIndex: 'terminalName'
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 150,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      productSearch2(status) {
        this.$refs.prochoose2.rowKey = 'id'
        let formconfig = [{
          key: 'userName',
          label: '用户账户'
        },
          {
            key: 'realName',
            label: '用户名称'
          }
        ]
        let tableconfig = {
          columns: [{
            title: '用户账户',
            align: 'left',
            dataIndex: 'userName',
            width: 120,
            ellipsis: true
          },
            {
              title: '用户名称',
              align: 'left',
              dataIndex: 'realName',
              width: 120,
              ellipsis: true
            }
          ],
          list: window._CONFIG['domianURL'] + '/cnUserController/getPageListUser',
          name:'拜访人员',
          multiple: false,
          columW: 10
        }

        // this.name = '用户'
        let dataSource = []
        if (this.form.getFieldValue('superiorUser')) {
          dataSource = [{
            userName: this.form.getFieldValue('superiorUser'),
            realName: this.form.getFieldValue('realsname')
          }]
        }
        this.$refs.prochoose2.isorter={  permflag: 'visit_plan_add' }
        this.$refs.prochoose2.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
      },
      rule: [{
        count: 0,
        actCode: '',
        orderNum: '',
        discount: '',
        gifts: []
      }],
      chara: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        visitDates: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        visitUserRealName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifyName: {
          rules: [{
            required: true,
            message: ''
          }]
        },
        classifytotName: {
          rules: [{
            required: true,
            message: ''
          }]
        }
      },
      url: {
        add: window._CONFIG['domianSfaURL'] + '/visit/sfaVisitPlan/saveOrUpdate',
        // savePosCust: window._CONFIG['domainURL'] + '/cnTerminalExtendController/saveTerminalExtend',
        saveUserRelation: window._CONFIG['domianURL'] + '/customerExtendController/saveExtendPos'
      }
    }
  },
  created() {
    console.log(this.keyState)
  },
  computed: {
    modalProps() {
      return {
        name: this.name
      }
    },
    modalProps1() {
      return {
        name: this.name
      }
    }
  },
  methods: {
    //首次拜访日期修改
    timeChange(obj, e) {
      // console.log(obj, e)
      obj.firstDate = e
      // console.log(obj)
      for (let i = 0; i < this.dataSource2; i++) {
        if (this.dataSource2[i].id == obj.id) {
          this.dataSource2[i] = obj
        }
      }
      console.log(this.dataSource2)
    },
    timeChange2(obj, e) {
      obj.firstDate = e
      // console.log(obj)
      for (let i = 0; i < this.dataSource; i++) {
        if (this.dataSource[i].id == obj.id) {
          this.dataSource[i] = obj
        }
      }
      console.log(this.dataSource)
    },
    //拜访频率修改
    onCellChange(key, dataIndex, value) {
      console.log(key)
      // for(let i =0;i<this.dataSource.length;i++){
      //   this.dataSource[i].visitFrequency=''
      // }
      let dataSource = [...this.dataSource]
      let target = dataSource.find(item => item.id === key)
      target[dataIndex] = value
      this.dataSource = dataSource
      console.log(this.dataSource)
    },
    onCellChange2(key, dataIndex, value) {
      console.log(key)
      let dataSource = [...this.dataSource2]
      let target = dataSource.find(item => item.id === key)
      target[dataIndex] = value
      this.dataSource2 = dataSource
      console.log(dataSource)
    },
    //经销商
    onSelectChange1(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    // 线路组
    onSelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows
    },
    chooseOk(e) {
      let key = this.dataSource.map(item => {
        return item.custCode
      })
      console.log(e)
      let that = this
      e.forEach(item => {
        if (key.indexOf(item.custCode) == -1) {
          item.code = item.custCode
          item.name = item.custName
          this.dataSource.push(item)
        }
      })
      console.log(this.dataSource)
    },
    //门店新增弹窗确认
    chooseOk2(e) {
      let key = this.dataSource2.map(item => {
        return item.terminalCode
      })
      console.log(e)
      let that = this
      e.forEach(item => {
        if (key.indexOf(item.terminalCode) == -1) {
          item.code = item.terminalCode
          item.name = item.terminalName
          this.dataSource2.push(item)
        }
      })
      console.log(this.dataSource2)
    },
    //线路组新增回显
    chooseOk3(e) {
      this.dataSource2 = []
      let key = this.dataSource2.map(item => {
        return item.groupCode
      })
      console.log(e)
      let that = this
      e.forEach(item => {
        if (key.indexOf(item.groupCode) == -1) {
          item.code = item.groupCode
          item.name = item.groupName
          this.dataSource2.push(item)
        }
      })
    },
    okbropro2(val, status, status2) {
      let objs = JSON.parse(JSON.stringify(val[0]))
      this.objs = objs
      this.form.setFieldsValue({
        visitUserName: objs.userName,
        visitUserRealName: objs.realName,
        visitPosName: objs.positionName,
        visitPosCode: objs.positionCode,
        visitOrgName: objs.departName,
        departCode: objs.departCode
      })
      this.visitPosCode = this.objs.positionCode
    },
    showModal(groupCode) {
      delete this.model.id
      this.visible = true
    },
    saveUserRelation(params) {
      console.log(params.posExtendVos)
      this.dataSource2 = params.posExtendVos
      // postAction(this.url.saveUserRelation, this.dataSource2).then(async (res) => {
      //   if (res.success) {
      //     this.$message.success(res.message)
      //     await this.loadData()
      //     this.$refs.ConfigModal.close()
      //   } else {
      //     this.$message.warning(res.message)
      //   }
      // }).finally(() => {
      //   this.$refs.ConfigModal.confirmLoading = false
      //   //that.close();
      // })

    },
    dataUserRess(params) {
      console.log(params)
      this.dataSource = params.posExtendVos
    },
    //经销商删除
    handleDelete(e) {
      let key = this.dataSource.map(item => {
        return item.id
      })
      this.dataSource.splice(key.indexOf(e.id), 1)

    },
    //门店删除
    handleDelete2(e) {
      console.log(this.dataSource2)
      let key = this.dataSource2.map(item => {
        return item.id
      })
      this.dataSource2.splice(key.indexOf(e.id), 1)
    },
    productSearch(status) {
      this.$refs.prochoose.rowKey = 'id'
      let formconfig = [{
        key: 'userName',
        label: '用户账户'
      },
        {
          key: 'realName',
          label: '用户名称'
        }
      ]
      let tableconfig = {
        columns: [{
          title: '用户账户',
          align: 'left',
          dataIndex: 'userName',
          width: 120,
          ellipsis: true
        },
          {
            title: '用户名称',
            align: 'left',
            dataIndex: 'realName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/cnUserController/getPageListUser',

        multiple: false,
        columW: 10
      }

      this.name = '用户'
      let dataSource = []
      if (this.form.getFieldValue('superiorUser')) {
        dataSource = [{
          userName: this.form.getFieldValue('superiorUser'),
          realName: this.form.getFieldValue('realsname')
        }]
      }
      this.$refs.prochoose.edit(formconfig, tableconfig, 'superiorUser', 'realsname', dataSource)
    },
    //有效期时间
    addInclude() {
      this.$refs.chooseModal1.show()
    },
    //周排除选择
    onChangeTime(e) {
      console.log(e)
      this.checkedList = e
    },
    // 日期处理
    dateRangeChange(e) {
      if (e) {
        console.log(moment(e).day(1).format('YYYY/MM/DD (dddd)'))
        this.model.weekIndex = this.getMonthWeek(e)
        let startDate = moment(e).week(moment(e).week).startOf('week').format('YYYY-MM-DD')
        let endDate = moment(e).week(moment(e).week).endOf('week').format('YYYY-MM-DD')
        if (startDate.split('-')[1] !== e.split('-')[1]) {
          startDate = moment(e).week(moment(e).week).startOf('month').format('YYYY-MM-DD')
        }
        if (endDate.split('-')[1] !== e.split('-')[1]) {
          endDate = moment(e).week(moment(e).week).endOf('month').format('YYYY-MM-DD')
        }
        this.form.setFieldsValue({
          visitDateStart: startDate,
          visitDateEnd: endDate,
        })
      } else {
        this.form.setFieldsValue({
          visitDateStart: '',
          visitDateEnd: '',
        })
      }
    },
    getMonthWeek(e) {
      //获取当前时间转字符串并用字符串方法split转数组，获取当前时间年、月、日
      let currentTimeArr = moment(e).month('YYYY-MM-DD').format('YYYY-MM-DD').split('-')
      //当前日期年
      let year = currentTimeArr[0]
      //当前日期月
      let month = currentTimeArr[1]
      //当前日期日
      let day = currentTimeArr[2]
      //获取本月有多少天
      let monthDay = moment(moment().month('YYYY-MM').format('YYYY-MM'), 'YYYY-MM').daysInMonth()
      //创建一个新数组，用来接收本月所有周未的日，如果本月最后一天不是周日那也算是周未
      let monthWeekend = []
      //如果本月的最后一天不是周日那也算作一周，push进数组
      if (moment(moment(`${year}-${month}-${monthDay} 00:00:00`).format()).day() != 0) {
        monthWeekend.push(monthDay)
      }
      //循环遍历当前月的每一天
      for (let i = 1; i <= monthDay; i++) {
        //获取每一天是周几
        let week = moment(moment(`${year}-${month}-${i} 00:00:00`).format()).day()
        //如果当前i==今天，就看之前的周末数组里有几个值就是第几周
        if (day == i) {
          var indexWeek = monthWeekend.length
        } else {
          //如果当前i不是今天并且当前i是周末，那就push进周末数组
          if (week == 0) {
            monthWeekend.push(i)
          }
        }
      }
      //返回当前日期是本月的第几周
      return indexWeek
    },

    add() {
      this.edit({})
    },
    edit(record, id) {
      console.log(record)
      if (record.makeType === 1) {
        this.keyState = '3'
      } else if (record.makeType === 2) {
        this.keyState = '1'
      } else if (record.makeType === 3) {
        this.keyState = '2'
      }
      this.form.resetFields()
      this.model = Object.assign({}, record)
      //循环日期
      for (let i = 0; i < this.model.detailVos.length; i++) {
        if (this.model.detailVos[i].clientType === 1) {
          this.model.detailVos[i].terminalCode = this.model.detailVos[i].clientCode
          this.model.detailVos[i].terminalName = this.model.detailVos[i].clientName
          this.dataSource2.push(this.model.detailVos[i])
        }
        if (this.model.detailVos[i].clientType === 2) {
          this.model.detailVos[i].custCode = this.model.detailVos[i].clientCode
          this.model.detailVos[i].custName = this.model.detailVos[i].clientName
          this.dataSource.push(this.model.detailVos[i])
        }
        if (this.model.detailVos[i].clientType === 3) {
          this.model.detailVos[i].groupCode = this.model.detailVos[i].clientCode
          this.model.detailVos[i].groupName = this.model.detailVos[i].clientName
          this.dataSource2.push(this.model.detailVos[i])
        }
      }
      console.log(this.dataSource, this.dataSource2)
      //职位编码
      this.visitPosCode = this.model.visitPosCode
      this.model.visitDateStarts = this.model.visitDateStart
      // this.model.visitDates = [this.model.visitDateStart, this.model.visitDateEnd]
      //排除周
      console.log(this.model.weekVos)
      if (!(this.model.weekVos === null)) {
        for (let i = 0; i < this.model.weekVos.length; i++) {
          this.checkedList.push(this.model.weekVos[i].exWeek)
        }
      }
      console.log(this.checkedList)
      this.visible = true
      // this.model.isRoll = this.model.isRoll + ''
      // this.model.isControl = this.model.isControl + ''
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'createBy', 'createName', 'createTime',
          'detailVos', 'orgName', 'orgCode', 'planCode', 'visitOrgCode', 'visitOrgName', 'visitPosCode', 'visitPosName', 'visitUserName',
          'visitUserRealName', 'weekVos', 'visitDateStarts','visitDateEnd','visitDateStart'))
      })
    }
    ,
    handleConfigTer() {
      this.dataSource.forEach(item => {
        this.$refs.orgShuttleModal.dataSource2.push({ custName: item.custName, custCode: item.custCode })
        this.$refs.orgShuttleModal.selectionRows.push({ custName: item.custName, custCode: item.custCode })
      })
      this.$refs.orgShuttleModal.visible = true
      this.$refs.orgShuttleModal.loadData()
    }
    ,
    handleConfig() {
      this.dataSource2.forEach(item => {
        this.$refs.cusShuttleModal.dataSource2.push({
          terminalName: item.terminalName,
          terminalCode: item.terminalCode
        })
        this.$refs.cusShuttleModal.selectionRows.push({
          terminalName: item.terminalName,
          terminalCode: item.terminalCode
        })
      })
      this.$refs.cusShuttleModal.visible = true
      this.$refs.cusShuttleModal.loadData()
    }
    ,
    //线路组新增
    handleConfigline() {
      this.dataSource2.forEach(item => {
        this.$refs.lineShuttleModal.dataSource2.push({ groupName: item.groupName, groupCode: item.groupCode })
        this.$refs.lineShuttleModal.selectionRows.push({ groupName: item.groupName, groupCode: item.groupCode })
      })
      this.$refs.lineShuttleModal.visible = true
      this.$refs.lineShuttleModal.loadData()
    }
    ,
    // savePosCust(params) {
    //
    //   postAction(this.url.savePosCust, params).then(async (res) => {
    //     if (res.success) {
    //       this.$message.success(res.message)
    //       await this.loadData()
    //       this.$refs.ConfigPosCust.close()
    //     } else {
    //       this.$message.warning(res.message)
    //     }
    //   }).finally(() => {
    //     this.$refs.ConfigPosCust.confirmLoading = false
    //     //that.close();
    //   })
    // },
    close() {
      this.$emit('close')
      this.form = this.$form.createForm(this)
      this.model = {}
      this.visible = false
      this.dataSource = []
      this.dataSource2 = []
      this.checkedList = []
      this.weekVos = []
      this.objs = []
      this.visitPosCode = ''
      this.disableSubmit = false
      console.log(this.form)
    }
    ,
    //上移下移
    moveSort(record, index, type) {
      let indexs = index
      if (type == 1) {
        indexs = index == this.dataSource2.length - 1 ? 0 : index + 1
      } else {
        indexs--
      }
      this.dataSource2[index] = this.dataSource2.splice(indexs, 1, this.dataSource2[index])[0]
    },
    handleOk() {
      const that = this
      // 触发表单验证
      //按网点新增
      if (this.keyState === '3') {
        //经销商
        let dataSource = this.dataSource.map(type => Object.assign({
          clientCode: type.custCode,
          clientName: type.custName,
          lng: type.longitude,
          lat: type.latitude,
          clientAddress: type.address, //地址
          telephone: type.telephone,  //电话号码
          clientType: 2
        }))
        //门店
        let dataSource2 = this.dataSource2.map(type => Object.assign({
          clientCode: type.terminalCode,
          clientName: type.terminalName,
          lng: type.longitude,
          lat: type.latitude,
          terminalLevel:type.terminalLevel,
          clientAddress: type.address, //地址
          telephone: type.telephone,  //电话号码
          clientType: 1
        }))
        // console.log(dataSource,dataSource2)
        this.detailVos = dataSource2.concat(dataSource)
        console.log(this.detailVos)
        this.makeType = 1
      }
      //按频率新增
      if (this.keyState === '2') {
        //经销商
        let dataSource = this.dataSource.map(type => Object.assign({
          clientCode: type.custCode,
          clientName: type.custName,
          lng: type.longitude,
          lat: type.latitude,
          visitFrequency: type.visitFrequency, //频率
          firstDate: type.firstDate, //首次拜访日期
          clientAddress: type.address, //地址
          telephone: type.telephone,  //电话号码
          clientType: 2
        }))
        //门店
        let dataSource2 = this.dataSource2.map(type => Object.assign({
          clientCode: type.terminalCode,
          clientName: type.terminalName,
          lng: type.longitude,
          lat: type.latitude,
          visitFrequency: type.visitFrequency,//频率
          firstDate: type.firstDate, //首次拜访日期
          clientAddress: type.address, //地址
          telephone: type.telephone,  //电话号码
          clientType: 1
        }))
        // console.log(dataSource,dataSource2)
        this.detailVos = dataSource2.concat(dataSource)
        console.log(this.detailVos)
        this.makeType = 3
      }
      //按线路组新增
      if (this.keyState === '1') {
        //线路
        let dataSource2 = this.dataSource2.map(type => Object.assign({
          clientCode: type.groupCode,
          clientName: type.groupName,
          lng: type.longitude,
          lat: type.latitude,
          clientType: 3
        }))
        // console.log(dataSource,dataSource2)
        this.detailVos = dataSource2
        console.log(this.detailVos)
        this.makeType = 2
      }
      for (let i = 0; i < this.checkedList.length; i++) {
        this.weekVos.push({ exWeek: this.checkedList[i] })
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let httpurl = ''
          httpurl = this.url.add
          let method = ''
          method = 'post'
          let formData = Object.assign(this.model, values)
          formData.visitPosCode = this.objs.positionCode
          formData.visitOrgCode = this.objs.departCode
          formData.visitOrgName = this.objs.departName
          formData.detailVos = this.detailVos
          formData.makeType = this.makeType  //新增类型
          // formData.visitDateStart = formData.visitDates[0] //开始时间
          // formData.visitDateEnd = formData.visitDates[1] //结束时间
          formData.weekVos = this.weekVos
          console.log(formData)
          //时间格式化
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
            that.close()
          })
        }
      })
    }
    ,
    handleCancel() {
      this.close()
    }
  }
}
</script>

<style scoped>
/deep/ .ant-col-sm-L-1 {
  width: 10.4%;
}

/deep/ .ant-col-sm-w-1 {
  width: 80%;
}
</style>
